import { defineStore } from "pinia";
import { ref, onBeforeMount, watch } from "vue";
import type { Size, ThemeType, Language } from "@/types/global";
export const useGlobalStore = defineStore(
  "global",
  () => {
    // 定义主题类型
    const themeType = ref<ThemeType>("light");
    watch(themeType, (newVal) => {
      if (newVal == "system") {
        const matches = window.matchMedia(
          "(prefers-color-scheme: dark)"
        ).matches;
        if (matches) {
          document.body.setAttribute("arco-theme", "dark");
        } else {
          document.body.removeAttribute("arco-theme");
        }
        return;
      }
      if (newVal == "dark") {
        document.body.setAttribute("arco-theme", "dark");
        return;
      }
      if (newVal == "light") {
        document.body.removeAttribute("arco-theme");
        return;
      }
    });
    const themeClick = (str: ThemeType) => {
      themeType.value = str;
    };
    onBeforeMount(() => {
      themeClick(themeType.value);
    });
    // 定义组件全局size
    const size = ref<Size>("medium");
    const sizeClick = (str: Size) => {
      size.value = str;
    };
    //定义语言
    const locale = ref<Language>("en_US");
    const localeClick = (str: Language) => {
      locale.value = str;
      location.reload();
    };
    return { themeType, size, locale, themeClick, sizeClick, localeClick };
  },
  {
    persist: {
      paths: ["themeType", "size", "locale"],
    },
  }
);
export const useUserStore = defineStore(
  "user",
  () => {
    // 定义用户信息
    const userInfo = ref<any>({});

    // 定义用户token
    const token = ref("");

    // 定义用户登录状态
    const isLogin = ref(false);

    // 定义用户退出登录方法
    const logout = () => {
      userInfo.value = {};
      token.value = "";
      isLogin.value = false;
    };

    return { userInfo, token, isLogin, logout };
  },
  {
    persist: {
      paths: ["userInfo", "token", "isLogin"],
    },
  }
);
